<?php
Namespace Cyfy\Modules\BasicContent;

class Content
{
    private $bcid = 0;
    private $title = '';
    private $content = '';
    private $creator = 0;
    private $created;
    private $updator = 0;
	private $updated;
    
    private $editable = false;
    private $deletable = false;
    
    private static $hasRun = false;
    
    public static function load($bcid, $language = '')
    {
        if($language == '')
        {            
            $language = \Cyfy\Language :: getActive(); 
        }
        
        $result = \dibi :: query("SELECT [bcid], [title], [content], [creator], [updator], [updated] FROM [:cyfy:BasicContent] WHERE [bcid] = %i", $bcid, " AND [language] = %s", $language);
    	
        if(count($result) == 0)
        {
            return false;
        }
        
        $content = new Content();
        
        $bc = (array) $result -> fetch();
        foreach($bc as $name => $value)
        {
            $content -> $name = $value;
        }
        
        // editable
		if(\Cyfy\Cyfy :: permission("BasicContent", "edit all") || (\Cyfy\Modules\Users\Current :: $uid == $content -> creator && \Cyfy\Cyfy ::  permission("BasicContent", "edit own")))
        {
			$content -> editable = true;
		}
        
        // deletable
		if(\Cyfy\Cyfy :: permission("BasicContent", "delete all") || (\Cyfy\Modules\Users\Current :: $uid == $content -> creator && \Cyfy\Cyfy ::  permission("BasicContent", "delete own")))
        {
			$content -> deletable = true;
		}
        
        return $content;
    }
    
    
    public static function deleteStatic($bcid, $language = '')
    {
        if($language == '')
        {            
            $language = \Cyfy\Language :: getActive(); 
        }
        $content = self :: load($bcid, $language = '');
        if(!$content) return false;
        
        return $content -> delete();
    }
    
    
    public function setContent($content)
    {
        $this -> content = $content;
    }
    
    public function setTitle($title)
    {
        $this -> title = $title;
    }
    
    public function setBCID($bcid)
    {
        $this -> bcid = $bcid;
    }
    
    public function getContent()
    {
        return $this -> content;
    }
    
    public function getTitle()
    {
        return $this -> title;
    }
    
        
    public function getCreator()
    {
        return $this -> creator;
    }
    
        
    public function getUpdated()
    {
        return $this -> updated;
    }
      
    public function __construct($title = '', $content = '', $language = '')
    {
        if($language == '')
        {            
            $language = \Cyfy\Language :: getActive(); 
        }
        
        
        $this -> title = $title;
        $this -> content = $content;
        $this -> language = $language;
        
        $this -> creator = \Cyfy\Modules\Users\Current :: $uid;
        $this -> created = new \DateTime(); 
    }
    
    
    /**
     * Checks, whether is current user permitted to delete the content.
     * @return bool TRUE, if deleting is possible.
     */
    public function isEditable()
	{
        return $this -> editable;
	}
    
    /**
     * Checks, whether is current user permitted to delete the content.
     * @return bool TRUE, if deleting is possible.
     */
	public function isDeletable()
	{
        return $this -> deletable;
	}
	
    
    public function save()
    {
        $existing = false;
        
        if($this -> bcid)
        {
            // content exists?
            $existing = self :: load($this -> bcid, $this -> language);
        }
        
        if(!$existing)
        {
            if(!\Cyfy\Cyfy ::  permission('BasicContent', 'add new'))
            {
                \Cyfy\Cyfy ::  noPermission();
                return false;
            }
            // ok, creating
            $values = array(
                'bcid' => $this -> bcid,
                'language' => $this -> language,
                'title' => $this -> title,
                'content' => $this -> content,
                'created' => $this -> created,
                'creator' => $this -> creator,
                'updated' => $this -> created
            );
            \dibi :: query("INSERT INTO [:cyfy:BasicContent] ", $values);
            return ($this -> bcid) ? $this -> bcid : \dibi :: insertId();
        }
        
        // permission?
        if(!$existing -> isEditable())
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
        
        // values
        $values = array(
            'content' => $this -> content,
            'updated' => new \DateTime(),
            'updator' => \Cyfy\Modules\Users\Current :: $uid
        );
        if($this -> title)
        {
            $values['title'] = $this -> title;
        }
        
		\dibi :: query("UPDATE [:cyfy:BasicContent] SET %a", $values, " WHERE [bcid] = %i ", $this -> bcid, " AND [language] = %s ", $this -> language);
        return true;
	}
    
    
    
    
    
    public function delete()
    {
        if(!$this -> isDeletable())
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
       
        \dibi :: query("DELETE FROM [:cyfy:BasicContent] WHERE [bcid] = '{$this -> bcid}' AND [language] = '{$this -> language}'");
        return true;
    }
    
    
    
    
    
    public function get($header = false, $noedit = false,  $nodelete = true)
    {
        $unique = uniqid();
        
        $class ="";
		
        // if user has the permission
        if($this -> isEditable() && !$noEdit)
        {
            $class = "  basicContentEditable";
            self :: editRunonce();   
        }
		$nodelete = ($nodelete) ? "noDelete" : "";
        
        $rtrn = "<div id=\"bc-{$unique}\" class=\"basicContent {$nodelete}{$class}\">\n".$this -> content . "\n</div>\n<input type=\"hidden\" id=\"bc-{$unique}-id\" value=\"{$this -> bcid}\" />\n";
        // text only?
        if($header==false){
            return $rtrn;
        }
        
        return "<{$header} class=\"basicContentName\"><span>{$this -> title}</span></{$header}>\n".$rtrn;
    }
    
    
    
    
    
    
    
     
    /**
     * Returns the content as string.
     * @param int BasicContent ID
     * @param string Language
     * @return array
     */
    public function getPage()
    {
        $unique = uniqid();
        
        // EDIT 
        $moreEditOptions = "";

        // if user has the permission to edit or delete
        if(($this -> isEditable() || $this -> isDeletable()))
        {
            self :: editRunonce();   
            
			$moreEditOptions .= "<input type=\"hidden\" id=\"bc-{$unique}-id\" value=\"{$this -> bcid}\" />";
            $moreEditOptions .= "<ul class=\"bcMoreEditOptions\">";
            // add edit buttons
            if($this -> isEditable()){
                $moreEditOptions .= "<li><a class=\"button\" href=\"" . \Cyfy\Cyfy ::  getPath('administration/BasicContent/pagesList/' . $this -> bcid) . "?language={$this -> language}\">" . Module :: t(430) . "</a></li>";
            }
            // add delete buttons
            if($this -> isDeletable()){
                $moreEditOptions .= "<li><a class=\"button\"  onclick=\"if(confirm('" . Module :: t(621,array($this -> title)) . "')){  Cyfy.ajax('BasicContent', 'deleteContent', '', 'bcid={$this -> bcid}&language={$this -> language}', 'Cyfy.redirectTo(\'\')') };\" href=\"#\">" . Module :: t(440) . "</a></li>";
            }
            $moreEditOptions .= "</ul>\n\n";
        }
        
        
        
        // title
        \Cyfy\Template :: setTitle($this -> title);
        
		return "<h2 class=\"basicContentName\">{$this -> title}</h2>\n<div id=\"bc-{$unique}\" class=\"basicContent basicContentEditable\">\n" . $this -> content . "\n</div>" . $moreEditOptions;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
	/**
     * When editing, this include_onces files.
     */
	static private function editRunonce()
	{
		if(self :: $hasRun)
        {
            return false;
        }
        self :: $hasRun = true;
        
        // if not tiny
        if(!\Cyfy\Modules :: isEnabled('TinyMCE')){
            return false;
        }
        
        \Cyfy\Cyfy ::  javaScript(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/BasicContent/edit.js"), "file");
        \Cyfy\Modules\TinyMCE\TinyMCE :: runonce();
    }
}

